/**
 * Grid封装 袁泉
 * 2018年4月15日16:09:55
 */
/*!
 * file : umGrid.js
 * gitee :
 * github :
 * author : 袁泉/Data.
 * version : v1.0.0
 * create time : 2018年6月18日18:43:01
 * update time : 2018年6月18日18:43:08
 */

;!(function ($, win, undefined) {
    var umGrid = {
        version: '1.0.2',
        debug: true,
        gridList:{},
        defaults: {
            renderTo:'',
            columnDefs:{},
            gridOptions:{}


        },
        ctrl : {
            a :function () {
                alert(this.id);
            }

        },
        init :function (param) {
            var that = this;
            var grid = {id:param};
            grid = $.extend(true,{},grid,that.ctrl);
            return grid;
        },
    };
    var Utils = {
        //替换
        reple: function (str, key, val) {
            //正则实现:
            if (str && typeof str == 'string') {
                var regExp = new RegExp(key, "g");
                return str.replace(regExp, val);
            } else {
                umUI.debug && console.error('替换方法出现异常替换:', str, typeof str);
            }
            return str;
            //递归实现：
            /* if (str.indexOf(key) > -1) {
                 return Utils.reple(str.replace(key, val), key, val);
             } else {
                 return str;
             }*/
        },
        //随机字符
        randomStr: function (len) {
            len = len || 32;
            var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz';
            /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
            var maxPos = $chars.length;
            var str = '';
            for (var i = 0; i < len; i++) {
                str += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return str;
        },
        isDom: function (obj) {
            return !!(obj && typeof window !== 'undefined' && (obj === window || obj.nodeType));
        },
        isJson: function (obj) {
            var isjson = (typeof (obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length);
            return isjson;
        },
        getNodeByClassName: function (node, className, parentWindow) {
            parentWindow = parentWindow || win;
            var that = this;
            if (node === parentWindow.document.body) {
                return null;
            }
            var cls = node.classList;
            if (cls.contains(className)) {
                return node;
            } else {
                return that.getNodeByClassName(node.parentNode, className);
            }
        },
        newGuid: function () {
            var guid = "";
            for (var i = 1; i <= 32; i++) {
                var n = Math.floor(Math.random() * 16.0).toString(16);
                guid += n;
                if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
                    guid += "-";
            }
            return guid;
        },
        array_remove_repeat: function (a) {
            var r = [];
            for (var i = 0; i < a.length; i++) {
                var flag = true;
                var temp = a[i];
                for (var j = 0; j < r.length; j++) {
                    if (temp === r[j]) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    r.push(temp);
                }
            }
            return r;
        },
        array_difference: function (a, b) {
            var that = this;
            var clone = a.slice(0);
            for (var i = 0; i < b.length; i++) {
                var temp = b[i];
                for (var j = 0; j < clone.length; j++) {
                    if (temp === clone[j]) {
                        clone.splice(j, 1);
                    }
                }
            }
            return that.array_remove_repeat(clone);
        },
        getParams: function (data) {
            var arr = [];
            for (var param in data) {
                arr.push(encodeURIComponent(param) + '=' + encodeURIComponent(data[param]));
            }
            arr.push(('v=' + Math.random()).replace('.'));
            return arr.join('&');
        },
        ajax: function (options) {
            // eq
            /*Utils.ajax({
                url: url ? url : grid.url,
                type: grid.type,
                data: grid.params,
                async: true,
                dataType: grid.dataType,
                before: function () {
                    that.loadTip(id);
                },
                success: function (text, xml) {
                    var data = JSON.parse(text);
                    setTimeout(function () {
                        that.createBodyContent(id, data);
                        that.closeLoadTip(id);
                    }, 0);
                },
                error: function (status) {
                    that.closeLoadTip(id);
                },
                complete: function () {
                }
            });*/
            var that = this;
            options = options || {};
            options.type = (options.type || "GET").toUpperCase();
            options.dataType = options.dataType || 'json';
            options.async = options.async || true;
            var params = that.getParams(options.data);
            var xhr;
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            } else {
                xhr = new ActiveXObject('Microsoft.XMLHTTP')
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    var status = xhr.status;
                    if (status >= 200 && status < 300) {
                        options.success && options.success(xhr.responseText, xhr.responseXML);
                    } else {
                        options.error && options.error(status);
                    }
                    options.complete && options.complete();
                }
            };
            if (options.type == 'GET') {
                options.before && options.before();
                xhr.open("GET", options.url + (options.url.indexOf("?") > -1 ? "&" : '?') + params, options.async);
                xhr.send(null)
            } else if (options.type == 'POST') {
                options.before && options.before();
                xhr.open('POST', options.url, options.async);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.send(params);
            }
        }
    };
    win.umGrid = {
        init:function (xParam) {
            return umGrid.init(xParam);
        }
    };
})(jQuery, window);



/*
;(function ($) {
    $.fn.extend({
        "initGrid": function (xParam) {
            var xDiv = this;
            var param = {}


            var columnDefs = [
                    {
                        colId: "checkbox",
                        hide: false,
                        headerName: "",
                        width: 35,
                        index: 0,
                        suppressSorting: true,
                        suppressMenu: true,
                        checkboxSelection: true,
                    },
                    {headerName: "类型", field: "type"},
                    {headerName: "标签", field: "label"},
                    {headerName: "值", field: "value"},
                    {headerName: "描述", field: "description"},
                    {headerName: "创建时间", field: "createDate"}
                ]
            ;

            /!*  var rowData = [
                  {type: "111", label: "Celica", value: 35000, description: 1, createDate: 2},
                  {type: "111", label: "Celica", value: 35000, description: 1, createDate: 2},
                  {type: "111", label: "Celica", value: 35000, description: 1, createDate: 2},
                  {type: "111", label: "Celica", value: 35000, description: 1, createDate: 2}
              ];*!/

            var gridOptions = {
                columnDefs: columnDefs,
                rowData: null,
                enableFilter: true,
                localeText: localeText_zh,
                enableServerSideSorting: false,
                enableSorting: true,
                enableColResize: true,//列可变化宽度
                suppressRowClickSelection: true,
                singleClickEdit: true,//单击编辑
                rowHeight: 35,//行高
                rowSelection: 'multiple',//多行选中方式(单行:single,multiple)
                headerHeight: 35,
                defaultColDef: {
                    editable: true
                },
                rowSelection: 'multiple',//多行选中方式(单行:single,multiple)
                // onRowDoubleClicked:function(params){//双击事件(跳转到查看页面)
                // },

                getRowStyle: function (params) {

                },
                onGridReady: function () {
                    gridOptions.api.sizeColumnsToFit();
                }
            };


            new agGrid.Grid(xDiv[0], gridOptions);


            $.ajax({
                url: '/admin/system/dict/list',
                type: 'post',
                success: function (data) {
                    var data = data.data;
                    var col = [];
                    col.push( {
                            colId: "checkbox",
                        hide: false,
                        headerName: "",
                        width: 35,
                        index: 0,
                        editable:false,
                        suppressSorting: true,
                        suppressMenu: true,
                        headerCheckboxSelection: true,//头部 checkbox
                        checkboxSelection: true//是否为checkbox
                    })
                    if (data[0]) {
                        $.each(data[0], function (i, v) {
                            var item = {
                                headerName: i,
                                field: i,
                                width: 100

                            }
                            col.push(item);

                        })
                    }
                    gridOptions.api.setColumnDefs(col)
                    gridOptions.api.doLayout()
                    console.log(col)

                    gridOptions.api.setRowData(data);
                    gridOptions.api.setFocusedCell(2, 'type');//设置焦点
                    gridOptions.api.startEditingCell({//设置编辑
                        rowIndex: 2,
                        colKey: 'type'
                    });
                }
            })
        }
    });
})(jQuery);*/

/*
var common_grid = function() {

    var initGrid = function(xGridId,xGridOptions,xGridColumns,xRowDoubleClickedCallback,xSetColumnDefsCallback,xCellRendererCallback,xExpandCallback,xCellStyleCallback,xColumnResizedCallback,xColumnMovedCallback,xCellValueChanged) {

        xGridOptions = { //Grid配置对象
            //groupUseEntireRow: false,
            //groupIncludeFooter: true,
            //groupColumnDef: {
            //    headerName: 'Country',
            //    cellRenderer: 'group',
            //    field: 'country'
            //},
            //groupRemoveSingleChildren: true,
            //animateRows: true,
            //groupDefaultExpanded: 1,
            //suppressAggFuncInHeader: true,
            enableFilter : true,
            enableServerSideSorting: false,
            enableSorting:true,
            enableColResize: true,//列可变化宽度
            rowSelection: 'single',//多行选中方式(单行:single,multiple)
            localeText: localeText_zh,//国际化(中文)
            getNodeChildDetails: getNodeChildDetails,
            onCellValueChanged:xCellValueChanged,  //单元格改变事件
            onRowDoubleClicked:function(params){//双击事件(跳转到查看页面)
                if (xRowDoubleClickedCallback == null) return;
                   xRowDoubleClickedCallback(params);
            },
            onColumnResized:function(params) {
                if(params.finished){
                    //(1)异步更新数据库
                    var param = {"TAC001" : params.column.colId.toUpperCase() ,"TAC002" : $("#"+xGridId).attr("name"), "TAC003": params.column.actualWidth};
                    result = Common_Ajax.ajaxFuncAsync("/admin/tabTac/updateTAC003" ,param );

                    //(2)更新缓存
                    var mTAC002 = JSON.parse(localStorage.getItem($("#"+xGridId).attr("name")));
                    for (var i = 0; i < mTAC002.length; i++){
                        if((mTAC002[i].tab002 == params.column.colId.toUpperCase()) || (mTAC002[i].tab002 == params.column.colId) || (mTAC002[i].tab002.toUpperCase() == params.column.colId.toUpperCase())){
                            mTAC002[i].tac003 = params.column.actualWidth;
                            break;
                        }
                    }
                    var str = JSON.stringify(mTAC002);
                    localStorage.setItem($("#"+xGridId).attr("name"),str);
                }
                if (xColumnResizedCallback == null) return;
                   xColumnResizedCallback(params);
            },
            onColumnMoved :function(params) {
                var mTAC004;
                var mColBefore = xGridOptions.columnApi.getDisplayedColBefore(xGridOptions.columnApi.getColumn(params.column.colId));// 前一个字段
                var mColAfter = xGridOptions.columnApi.getDisplayedColAfter(xGridOptions.columnApi.getColumn(params.column.colId)); //后一个字段

                if (mColBefore == null)  return;
                else if (mColAfter == null)  mTAC004 = mColBefore.colDef.index + 0.1 ;
                else{
                    mTAC004 =  mColBefore.colDef.index + ((mColAfter.colDef.index - mColBefore.colDef.index) / 2) ;
                }

                //(1)异步更新数据库
                var param = {"TAC001" : params.column.colId.toUpperCase() ,"TAC002" : $("#"+xGridId).attr("name"), "TAC004": mTAC004};
                result = Common_Ajax.ajaxFuncAsync("/admin/tabTac/updateTAC004" ,param );

                //(2)更新缓存
                var mTAC002 = JSON.parse(localStorage.getItem($("#"+xGridId).attr("name")));
                for (var i = 0; i < mTAC002.length; i++){
                    if((mTAC002[i].tab002 == params.column.colId.toUpperCase()) || (mTAC002[i].tab002 == params.column.colId) || (mTAC002[i].tab002.toUpperCase() == params.column.colId.toUpperCase())){
                        mTAC002[i].tac004 = mTAC004;
                        break;
                    }
                }
                var str = JSON.stringify(mTAC002);
                localStorage.setItem($("#"+xGridId).attr("name"),str);
                if (xColumnMovedCallback == null) return;
                xColumnMovedCallback(params);
            },
            onGridReady: function(params) {
                params.api.sizeColumnsToFit();
            },
            onCellClicked:function(params){
                if(params.node.group) {
                    params.node.setSelected(true, true);
                }
            },
            getRowStyle: function(params) {
                if (params.node.group) {
                    return {'font-weight': 'bold'}
                }
            }
        };
//			xGridOptions["rowSelection"] = 'multiple';
//			xGridOptions["groupSelectsChildren"] = true;
// 			xGridOptions["suppressRowClickSelection"] = true;
        $("#"+xGridId).html("");
        new agGrid.Grid(document.querySelector("#"+xGridId), xGridOptions);


        common_grid.paging(xGridId,xGridOptions,xGridColumns,xSetColumnDefsCallback,xCellRendererCallback,xExpandCallback,xCellStyleCallback);
        common_grid.setGirdHeight(xGridId);
        $("#rightIbox").height( $("#clientIbox").height());
        gridOptions = xGridOptions;
        return xGridOptions;
    };

    function getNodeChildDetails(rowItem) {
        if (rowItem.group) {
            return {
                group: true,
                expanded: rowItem.expanded === 'true',
                children: rowItem.children,
                field: 'group',
                key: rowItem.group
            };
        } else {
            return null;
        }
    }

    //创建列
    function createCols(cols,xGridId,xGridColumns,xCellRendererCallback,xCellStyleCallback) {

        xGridColumns = [];
        var mTAC002 = JSON.parse(localStorage.getItem($("#"+xGridId).attr("name")));
        if (isShowCheckBox) {
            var checkbox = {colId : "checkbox", hide:false,headerName: "", width: 35, index : 0, suppressSorting: true, suppressMenu: true,
                checkboxSelection: true,headerCellRenderer: headerCellCheckBoxRender
            };
            xGridColumns.push(checkbox);
        }else {

        }
        for(var col in cols){
            for (var i = 0; i < mTAC002.length; i++){
                if((mTAC002[i].tab002 == col.toUpperCase()) || (mTAC002[i].tab002 == col)|| (mTAC002[i].tab002.toUpperCase() == col.toUpperCase())){
                    // if(col.toUpperCase().indexOf("IDS") >= 0 ) break;  //表主键 不显示
                    if(mTAC002[i].tac005 == "1"){  //显示否
                        if (groupCol == col) {  //行分组 comparator: agGrid.defaultGroupComparator,
                            var colDef = { hide:false, cellClass:'ag-cell-left', headerName: mTAC002[i].tab003, colId :col ,field: col, width: mTAC002[i].tac003,index:mTAC002[i].tac004,cellRenderer: 'group' ,cellStyle:xCellStyleCallback,cellRendererParams: {
                                innerRenderer: innerCellRenderer
                            } };
                        }else if (groupHeaderKey.indexOf(col)  > -1) { //列分组
                            var groupHeaderValue = [];//需要分组的子信息
                             groupHeaderValue = groupHeader[col];
                            var children = [];   //子信息的定义
                            for (var j = 0 ;j<groupHeaderValue.length;j++){
                                var childrenValue=groupHeaderValue[j];
                                for(var h = 0 ;h< mTAC002.length;h++){
                                    if(childrenValue.toUpperCase()==mTAC002[h].tab002.toUpperCase() ){
                                        if (groupCol.toUpperCase() == mTAC002[h].tab002.toUpperCase()) {
                                            children.push({ hide:false, cellClass:'ag-cell-left', headerName:mTAC002[h].tab003,
                                                colId :groupCol ,field: groupCol, width: mTAC002[h].tac003,index:mTAC002[h].tac004,cellRenderer: 'group' });
                                               break;
                                        }else {
                                            children.push( { hide:false,  headerName: mTAC002[h].tab003,
                                                colId :childrenValue ,field:childrenValue,
                                                width: mTAC002[h].tac003,index:mTAC002[h].tac004 ,cellRenderer: xCellRendererCallback}  );
                                            break;
                                        }
                                    }
                                }
                            }
                            var colDef =  {headerName:  mTAC002[i].tab003,index:mTAC002[i].tac004,
                                children:children
                            };
                        }else {
                            if (xCellRendererCallback == null){
                                    var colDef = {hide:false,editable: isEdiTable?(mTAC002[i].tac008 != "1" ?  false:true):false , headerName: mTAC002[i].tab003, colId :col ,field: col, width: mTAC002[i].tac003,index:mTAC002[i].tac004 };
                                }
                            else {
                                var colDef = {hide: false, editable: isEdiTable?(mTAC002[i].tac008 != "1" ? false : true):false, headerName: mTAC002[i].tab003, colId: col, field: col, width: mTAC002[i].tac003, index: mTAC002[i].tac004, cellRenderer: xCellRendererCallback,cellStyle:xCellStyleCallback
                                    };
                            }
                        }
                        xGridColumns.push(colDef);
                    }
                    else {
                        if (groupCol == col) {
                            var colDef = { hide:true, cellClass:'ag-cell-left', headerName: mTAC002[i].tab003 , colId :col ,field: col, width: mTAC002[i].tac003,index:mTAC002[i].tac004,cellRenderer: 'group',cellStyle:xCellStyleCallback};
                        }else{
                            if (xCellRendererCallback == null){
                                var colDef = { hide:true, headerName: mTAC002[i].tab003 , colId :col ,field: col, width: mTAC002[i].tac003,index:mTAC002[i].tac004 };
                            }
                            else {
                                var colDef = { hide:true, headerName: mTAC002[i].tab003 , colId :col ,field: col, width: mTAC002[i].tac003,index:mTAC002[i].tac004,cellRenderer: xCellRendererCallback ,cellStyle:xCellStyleCallback};
                            }
                        }
                        xGridColumns.push(colDef);
                    }
                    break;
                }
            }
        }
        xGridColumns.sort(function(a,b){return a.index-b.index});
        return xGridColumns;
    };

    //分页方法
    var paging =  function(xGridId,xGridOptions,xGridColumns,xSetColumnDefsCallback,xCellRendererCallback,xExpandCallback,xCellStyleCallback){
        var dataArray = $("#gridForm").serializeArray();
        dataArray.push({name:"isAjax",value:"1"});
        $.ajax($("#"+xGridId).attr("action"), {
            data:dataArray,
            success: function (response) {
                //3、得到数据以后 要显示到Grid中 （通过Grid的API) setRowData
                var page = response;//得到json数据
                if (isGroup){

                    var dataArray = $("#gridForm").serializeArray();
                    dataArray.push({name:"isAjax",value:"col"});
                    $.ajax($("#"+xGridId).attr("action"), {
                        data:dataArray,
                        success: function (response) {
                            //3、得到数据以后 要显示到Grid中 （通过Grid的API) setRowData
                            var colDefs = createCols(response[0],xGridId,xGridColumns,xCellRendererCallback,xCellStyleCallback);
                            if (xSetColumnDefsCallback != null)
                                xSetColumnDefsCallback(colDefs,page);
                            xGridOptions.api.setColumnDefs(colDefs);

                            xGridOptions.api.setRowData(page);
                            if (xExpandCallback != null)
                                xExpandCallback();
                        }
                    });
                }else{
                    var colDefs = createCols(page[0] ,xGridId,xGridColumns,xCellRendererCallback,xCellStyleCallback);
                    if (xSetColumnDefsCallback != null)
                        xSetColumnDefsCallback(colDefs);
                    xGridOptions.api.setColumnDefs(colDefs);
                    xGridOptions.api.setRowData(page);
                }
            }
        });
    };

    //带工具栏
    var setGirdHeight = function(winId){
        if (isLayer){
            var gridHeight1;
            // 窗体高度
            if ((document.body) && (document.body.offsetHeight)){
                gridHeight1 = document.body.offsetHeight;
            } else if (window.innerHeight){
                gridHeight1 = window.innerHeight;
            }
            $("#" + winId).height(gridHeight1- 130 - gridHeight);
        }else {
            $("#" + winId).height(localStorage.getItem('gridHeight')- 30 - gridHeight);
        }

    };

    var onFilterChanged = function(newFilter) {
        filterCount++;
        var filterCountCopy = filterCount;
        setTimeout(function () {
            if (filterCount === filterCountCopy) {
                gridOptions.api.setQuickFilter(newFilter);
            }
        }, 300);
    };

    var filterDoubleClicked = function(event) {
        setInterval(function () {
            gridOptions.api.ensureIndexVisible(Math.floor(Math.random() * 100000));
        }, 4000);
    };

    return {
        setGirdHeight: setGirdHeight,
        paging:paging,
        filterDoubleClicked :filterDoubleClicked,
        onFilterChanged:onFilterChanged,
        initGrid :initGrid,
    };

}();*/
